import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';

/// 网络连接状态服务
class ConnectivityService {
  static final ConnectivityService _instance = ConnectivityService._internal();
  factory ConnectivityService() => _instance;
  ConnectivityService._internal();

  final Connectivity _connectivity = Connectivity();
  final StreamController<ConnectivityResult> _connectionStatusController =
      StreamController<ConnectivityResult>.broadcast();

  Stream<ConnectivityResult> get connectionStatus =>
      _connectionStatusController.stream;

  ConnectivityResult _connectionStatus = ConnectivityResult.none;
  ConnectivityResult get connectionStatusValue => _connectionStatus;

  bool get isOnline => _connectionStatus != ConnectivityResult.none;

  /// 初始化网络监听
  Future<void> initialize() async {
    // 监听网络状态变化
    _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);

    // 获取初始连接状态
    final results = await _connectivity.checkConnectivity();
    _connectionStatus = results.first; // 取第一个结果
    _connectionStatusController.add(_connectionStatus);
  }

  /// 更新连接状态
  void _updateConnectionStatus(List<ConnectivityResult> results) {
    // 使用第一个结果作为当前连接状态
    _connectionStatus = results.first;
    _connectionStatusController.add(_connectionStatus);
  }

  /// 检查当前连接状态
  Future<ConnectivityResult> checkConnection() async {
    final results = await _connectivity.checkConnectivity();
    _connectionStatus = results.first; // 取第一个结果
    return _connectionStatus;
  }

  /// 释放资源
  void dispose() {
    _connectionStatusController.close();
  }
}